﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using MvcEnrollment.Models;
using System.Xml;
using MvcEnrollment.Helpers;

namespace MvcEnrollment.Controllers
{
    public class StudentController : Controller
    {
        //private CourseDBContext db = new CourseDBContext();
        private EnrollmentEntities1 db = new EnrollmentEntities1();
        //
        // GET: /Student/

        public ActionResult Index()
        {
            return View(db.Students.ToList());
        }

        //
        // GET: /Student/Details/5

        public ActionResult Details(int id = 0)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        //render terms and conditions
        public ActionResult Term()
        {
            return View();
        }

        //
        // GET: /Student/Confirmation
        //confirmation page, display receipt
        public ActionResult Confirmation()
        {
            var pidv = Request.Cookies["paymentId"].Value;
            int pid = 0;
            int.TryParse(pidv, out pid);
            Course_Price course_price = db.Course_Price.Find(pid);
            if (course_price == null)
            {
                return HttpNotFound();
            }
            //retrieve cart content
            getPayInfo(course_price);

            var cidv = Request.Cookies["courseId"].Value;
            int cid = 0;
            int.TryParse(cidv, out cid);
            Course course = db.Courses.Find(cid);
            if (course == null)
            {
                return HttpNotFound();
            }
            ViewData["courseName"] = course.Course_Name;
            ViewData["institution"] = course.Course_Provider;
            return View();
        }

        //retrieve cart content, concatenate payment details
        public void getPayInfo(Course_Price course_price)
        {
            var duration = String.Format("{0:n0}", course_price.Total_Recurrings);
            if (course_price.Payment_Type.Equals("Fully"))
            {
                ViewData["PDetails"] = "Full Installment: $" + course_price.Total_Price;
                ViewData["totalAmount"] = course_price.Total_Price;
            }
            else if (course_price.Payment_Type.Equals("Monthly"))
            {
                if (course_price.Deposit != null && course_price.Deposit != 0)
                {
                    ViewData["PDetails"] = "Monthly Installment: $" + course_price.Deposit + " deposit and after 30 days, $" + course_price.Recurring_Amount + " per month for " + duration + " months";
                    ViewData["totalAmount"] = course_price.Deposit;
                }
                else
                {
                    ViewData["PDetails"] = "Monthly Installment: $" + course_price.Recurring_Amount + " every 30 days for " + duration + " months";
                    ViewData["totalAmount"] = course_price.Recurring_Amount;
                }
            }
            else if (course_price.Payment_Type.Equals("Weekly"))
            {
                if (course_price.Deposit != null && course_price.Deposit != 0)
                {
                    ViewData["PDetails"] = "Weekly Installment: $" + course_price.Deposit + " deposit and after 7 days, $" + course_price.Recurring_Amount + " per week for " + duration + " weeks";
                    ViewData["totalAmount"] = course_price.Deposit;
                }
                else
                {
                    ViewData["PDetails"] = "Weekly Installment: $" + course_price.Recurring_Amount + " every 7 days for " + duration + " weeks";
                    ViewData["totalAmount"] = course_price.Recurring_Amount;
                }
            }
        }

        //save course and payment IDs in Cookies for further operation, redirect to personal and card form page
        public ActionResult RedirectCreate()
        {
            HttpCookie hc = new HttpCookie("courseId", Request.Form["courseId"]);
            Response.Cookies.Add(hc);
            HttpCookie hc2 = new HttpCookie("paymentId", Request.Form["paymentId"]);
            Response.Cookies.Add(hc2);
            return RedirectToAction("Create", "Student");
        }

        //
        // GET: /Student/Create
        public ActionResult Create()
        {
            ViewData["titleList"] = getTitleItems("Mr");
            //ViewBag.countries = db.Countries.ToList();
            var pidv = Request.Cookies["paymentId"].Value;
            int pid = 0;
            int.TryParse(pidv, out pid);
            Course_Price course_price = db.Course_Price.Find(pid);
            if (course_price == null)
            {
                return HttpNotFound();
            }
            //retrieve cart content for display at the top of personal and card form
            getPayInfo(course_price);
            var cidv = Request.Cookies["courseId"].Value;
            int cid = 0;
            int.TryParse(cidv, out cid);
            Course course = db.Courses.Find(cid);
            if (course == null)
            {
                return HttpNotFound();
            }
            ViewData["courseName"] = course.Course_Name;
            return View();
        }

        private Payment fillPaymentRecord(Order order, string trxnReference, Course_Price course_price)
        {
            Payment payment = new Payment();
            payment.Order = order;
            payment.InvoiceReference = trxnReference;
            payment.Outstanding_Amount = course_price.Total_Price;
            payment.Order_Status = "Pending";
            payment.Order_Process_Type = "Automatic";
            payment.Actual_Deposit = course_price.Deposit;
            payment.Actual_Discount = (int)course_price.Discount;
            payment.Actual_Price = course_price.Total_Price;
            payment.Actual_Recurring_Amount = course_price.Recurring_Amount;
            payment.Actual_Recurring_Weeks = course_price.Total_Recurrings;
            payment.Order_Start_Date = DateTime.Today.Date;
            if (course_price.Payment_Type.Equals("Fully"))
            {
                payment.Order_End_Date = DateTime.Today.AddDays(1).Date;
            }
            else
            {
                int interval = 7;
                if (course_price.Payment_Type.Equals("Monthly"))
                {
                    interval = 30;
                }
                int duration = course_price.Total_Recurrings.Value;
                if (course_price.Deposit == 0 || course_price == null)
                {
                    duration -= 1;
                }
                payment.Order_End_Date = DateTime.Today.AddDays(interval * duration + 1 + 1).Date;
            }
            payment.Payment_Type = course_price.Payment_Type;
            payment.Created_By = 0;
            return payment;
        }

        //
        // POST: /Student/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Student student)
        {
            //generate dropdownlist content and save user input data for refreshing page
            ViewData["titleList"] = getTitleItems(Request.Form["titleList"].ToString());
            //ViewBag.countries = db.Countries.ToList();
            ViewData["country"] = Request.Form["country"];
            ViewData["firstName"] = Request.Form["firstName"];
            ViewData["lastName"] = Request.Form["lastName"];
            ViewData["phone"] = Request.Form["phone"];
            ViewData["email"] = Request.Form["email"];
            ViewData["state"] = Request.Form["state"];
            ViewData["postcode"] = Request.Form["postcode"];
            ViewData["Addr1"] = Request.Form["Addr1"];
            ViewData["Addr2"] = Request.Form["Addr2"];
            ViewData["Suburb"] = Request.Form["Suburb"];
            ViewData["bd"] = Request.Form["bd"];
            ViewData["bm"] = Request.Form["bm"];
            ViewData["by"] = Request.Form["by"];
            ViewData["cardName"] = Request.Form["cardName"];
            ViewData["cardNum"] = Request.Form["cardNum"];
            ViewData["exM"] = Request.Form["exM"];
            ViewData["exY"] = Request.Form["exY"];
            ViewData["cvn"] = Request.Form["cvn"];

            //generate student model
            student.Title = Request.Form["titleList"];
            student.Country = Request.Form["country"];
            student.First_Name = Request.Form["firstName"];
            student.Last_Name = Request.Form["lastName"];
            student.Phone = Request.Form["phone"];
            student.Email = Request.Form["email"];
            student.State = Request.Form["state"];
            int pc = 0;
            int.TryParse(Request.Form["postcode"], out pc);
            student.Postcode = pc;
            var birthday = Request.Form["bd"] + "/" + Request.Form["bm"] + "/" + Request.Form["by"];
            DateTime b = new DateTime();
            DateTime.TryParse(birthday, out b);
            student.Birthday = b;
            var address = Request.Form["Addr1"] + " " + Request.Form["Addr2"] + " " + Request.Form["Suburb"];
            student.Address = address;

            student.Created_By = 0;
            student.Created_Date = DateTime.Today.Date;

            int cid = 0;
            int.TryParse(Request.Cookies["courseId"].Value, out cid);
            int pid = 0;
            int.TryParse(Request.Cookies["paymentId"].Value, out pid);

            //get Course_Price object
            Course_Price course_price = db.Course_Price.Find(pid);     
            
            if (ModelState.IsValid)
            {
                string trxnReference = "";
                

                //student's first submittion
                if (Session["student"] == null)
                {
                    //create order
                    Order order = new Order();
                    order.Course_Id = cid;
                    order.Course_Price_Id = pid;
                    order.Created_By = 0;
                    order.Created_Date = DateTime.Today.Date;
                    order.Student = student;

                    //create eway customised trxn number by using combination of date and random number
                    string date = DateTime.Now.ToString("ddMMyyyy");
                    trxnReference = date + RandamNumberGenerator();
                    Session["trxnRef"] = trxnReference;

                    //create payment
                    Payment payment = new Payment();
                    payment = fillPaymentRecord(order, trxnReference, course_price);

                    db.Students.Add(student);
                    db.Orders.Add(order);
                    db.Payments.Add(payment);
                    db.SaveChanges();

                }
                    //student resubmit forms
                else
                {
                    trxnReference = Session["trxnRef"].ToString(); 
                }
                    


                //read card info
                string cardName = Request.Form["cardName"];
                string cardNum = Request.Form["cardNum"];
                string exM = Request.Form["exM"];
                //direct payment requires 2 characters for expiry year, while recurring payment requires 4
                string exY = Request.Form["exY"];
                string exY2 = exY.Substring(2, 2);
                string cvn = Request.Form["cvn"];

                //store payer info for receipt display
                Session["PayerName"] = student.First_Name + " " + student.Last_Name;
                Session["PayerAddress"] = student.Address + " " + student.State + " " + student.Country;
                Session["PayerEmail"] = student.Email;
                
                
                //direct payment
                if (course_price.Payment_Type.Equals("Fully"))
                {
                    //send request and receive response from eWAY for direct payment
                    GatewayRequest ewayReq = getEWayDirectPaymentRequest(student, trxnReference, course_price, cardName, cardNum, exM, exY2, cvn);
                    GatewayResponse ewayRes = getEWayDirectPaymentResponse(ewayReq);
                    //GatewayResponse ewayRes = ProcessDirectPayment(student, trxnReference, course_price, cardName, cardNum, exM, exY2, cvn);

                    //find the perivous payments by invoice refernce
                    Payment findPayment = new Payment();
                    var paymentList = from p in db.Payments
                                      where p.InvoiceReference.Equals(trxnReference)
                                      select p;
                    findPayment = paymentList.SingleOrDefault();

                    //save eway response to transaction
                    Transaction direct = new Transaction();
                    direct.Payment = findPayment;
                    direct.Transaction_Date = DateTime.Today.Date;
                    direct.ewayTrxnError = ewayRes.Error;
                    direct.ewayTrxnStatus = ewayRes.Status.ToString();
                    long tn = 0;
                    long.TryParse(ewayRes.TransactionNumber, out tn);
                    direct.ewayTrxnNumber = tn;
                    //may need to covernt amount to deciaml then divided by 100 from cent to dollar.
                    direct.Transaction_Amount = ewayRes.Amount/100;
                    long tr = 0;
                    long.TryParse(ewayRes.InvoiceReference, out tr);
                    direct.ewayTrxnReference = tr;                                       

                    db.Transactions.Add(direct);
                    //db.SaveChanges();

                    //if transaction succeed
                    if (ewayRes.Status == true)
                    {
                        //clear session, forget the student
                        Session["student"] = null;
                        Session["trxnRef"] = null;

                        findPayment.Order_Status = "Approved";
                        db.Entry(findPayment).State = EntityState.Modified;
                        db.SaveChanges();
                        return RedirectToAction("Confirmation");
                    }
                    //errors occur during transaction via eway
                    else
                    {
                        //remember the student, don't save the student, order, payment records again
                        Session["student"] = student;
                        string reqXML = ewayReq.ToTransactionXml();
                        string resXML = ewayRes.ToXml();
                        //log XML files/////////////////////////////////////////////////////////////////
                        Transaction_Log tran_log = new Transaction_Log();
                        tran_log.Transaction = direct;
                        tran_log.CC_Request = reqXML;
                        tran_log.eWay_Response = resXML;
                        tran_log.Created_By = 0;
                        tran_log.Created_Date = DateTime.Today.Date;
                        db.Transaction_Log.Add(tran_log);

                        ModelState.AddModelError("PaymentError", ewayRes.Error + " Please check your credit card infomation and try again.");
                    }
                    db.SaveChanges();
                }
                //recurring payment for monthly or weekly
                else if (course_price.Payment_Type.Equals("Monthly") || course_price.Payment_Type.Equals("Weekly"))
                {
                    //find the perivous payments by invoice refernce
                    Payment findPayment = new Payment();
                    var paymentList = from p in db.Payments
                                      where p.InvoiceReference.Equals(trxnReference)
                                      select p;
                    findPayment = paymentList.SingleOrDefault();

                    //haven't successfully create rebill customer yet
                    if (findPayment.Rebill_Customer_Id == 0 || findPayment.Rebill_Customer_Id == null) {
                        var rebillCustomer = CreateRebillCustomer(student);
                        
                        //creating rebill customer fails
                        if (rebillCustomer.Result.Equals("Fail"))
                        {
                            //remember the student, don't save the student, order, payment records again
                            Session["student"] = student;
                            ModelState.AddModelError("PaymentError", rebillCustomer.ErrorDetails + " Please check your personal information and try again.");
                        }
                        else
                        {
                            string rebillCustomerID = rebillCustomer.RebillCustomerID;

                            //create RebillCustomer succeed, save rebillCustomerID in payment record
                            int rcid = 0;
                            int.TryParse(rebillCustomerID, out rcid);
                            findPayment.Rebill_Customer_Id = rcid;
                        }
                    }
                    //rebill customer successfully created, but no rebill event yet
                    if ((findPayment.Rebill_Customer_Id != 0 && findPayment.Rebill_Customer_Id != null) && (findPayment.Rebill_Id == 0 || findPayment.Rebill_Id == null))
                    {
                        string rebillCustomerID = findPayment.Rebill_Customer_Id.ToString();
                        var rebillEvent = CreateRebillEvent(student, course_price, trxnReference, rebillCustomerID, cardName, cardNum, exM, exY, cvn);
                        //rebill event successfully created
                        if (rebillEvent.Result.Equals("Success"))
                        {
                            //store rebill ID in payment
                            string rebillId = rebillEvent.RebillID;                            
                            int rid = 0;
                            int.TryParse(rebillId, out rid);
                            findPayment.Rebill_Id = rid;

                            //create transaction
                            var rec_trans = QueryTransactions(rebillCustomerID, rebillId);
                            foreach (var item in rec_trans)
                            {
                                Transaction recurring = new Transaction();
                                recurring.Payment = findPayment;
                                recurring.Transaction_Date = item.TransactionDate;
                                decimal a = 0;
                                decimal.TryParse(item.Amount, out a);
                                recurring.Transaction_Amount = a;
                                recurring.ewayTrxnStatus = item.Status.ToString();
                                recurring.ewayTrxnError = item.TransactionError;
                                long tn = 0;
                                long.TryParse(item.TransactionNumber, out tn);
                                recurring.ewayTrxnNumber = tn;
                                db.Transactions.Add(recurring);
                            }

                            //save into database
                            db.Entry(findPayment).State = EntityState.Modified;                            
                            db.SaveChanges();

                            //clear student
                            Session["student"] = null;
                            Session["trxnRef"] = null;
                            
                            return RedirectToAction("Confirmation");
                        }
                            //creating rebill event fails
                        else
                        {
                            //remember the student, don't save the student, order, payment records again
                            Session["student"] = student;
                            ModelState.AddModelError("PaymentError", rebillEvent.ErrorDetails + " Please check your credit card infomation and try again.");

                            //log XML file///////////////////////////////////////////////////////////////////////////////////////////////
                        }
                        db.SaveChanges();
                    }                    
                }

            }
            Course course = db.Courses.Find(cid);
            ViewData["courseName"] = course.Course_Name;
            getPayInfo(course_price);
            return View(student);
        }

        //create rebill customer
        public ewayRecurringWebService.CustomerDetails CreateRebillCustomer(Student student)
        {
            var soap = new ewayRecurringWebService.manageRebillSoapClient("manageRebillSoap");
            soap.Open();
            var header = new ewayRecurringWebService.eWAYHeader();
            header.eWAYCustomerID = "87654321";
            header.Username = "test@eway.com.au";
            header.Password = "test123";
            var customer = new ewayRecurringWebService.CustomerDetails();
            customer = soap.CreateRebillCustomer(ref header, student.Title, student.First_Name, student.Last_Name, student.Address, "", student.State,
                "", student.Postcode.ToString(), student.Country, student.Email, "", student.Phone, "", student.First_Name + ' ' + student.Last_Name, "", "", "");
            soap.Close();
            return customer;
        }

        //create rebill event
        public ewayRecurringWebService.RebillEventDetails CreateRebillEvent(Student student, Course_Price course_price, string trxnReference, string rebillCustomerID, string cardName, string cardNum, string exM, string exY, string cvn)
        {
            var soap = new ewayRecurringWebService.manageRebillSoapClient("manageRebillSoap");
            soap.Open();
            var header = new ewayRecurringWebService.eWAYHeader();
            //test gateway header. In real use please switch to CC eWAY account.
            header.eWAYCustomerID = "87654321";
            header.Username = "test@eway.com.au";
            header.Password = "test123";

            //set up payment interval
            int interval = 7;
            if (course_price.Payment_Type.Equals("Monthly"))
            {
                interval = 30;
            }

            //payment with or without deposit
            int duration = (int)course_price.Total_Recurrings;
            var initAmt = "";
            var recurAmt = "";
            //payment with deposit
            if (course_price.Deposit != 0 && course_price.Deposit != null)
            {
                //$10.00 is presented as 1000 for eway
                //set initial and recurring amount
                string d = course_price.Deposit.ToString().Replace(".", "");
                initAmt = d;
                string a = course_price.Recurring_Amount.ToString().Replace(".", "");
                recurAmt = a;
            }
            //payment without deposit
            else
            {
                //$10.00 is presented as 1000 for eway
                //If there is no deposit needed, the initial payment would be the first week payment, then duration should be reduced by 1
                string a = course_price.Recurring_Amount.ToString().Replace(".", "");
                initAmt = a;
                recurAmt = a;
                duration = duration - 1;
            }
            //initial date uses next day of today's date.
            var initDate = DateTime.Today.AddDays(1).Date.ToString("dd/MM/yyyy");
            //start date equals initial date plus interval
            DateTime startDateTime = new DateTime();
            startDateTime = DateTime.Today.AddDays(interval + 1);
            var startDate = startDateTime.ToString("dd/MM/yyyy");

            //end date equals start date plus interval times duration, since first recurring payment paid on start date, no payment on end date, result minus one
            //Eg, pay for 3 weeks, first payment on 1st, last payment on 15th, end date would be 16th.
            //enddate = 1+7*(3-1) + 1
            var rebillEndDate = startDateTime.AddDays(interval * (duration - 1) + 1).ToString("dd/MM/yyyy");

            //recurring on every interal days
            //interval type 1=days, 2=weeks, 3=months, 4=years
            var rebillIntervalType = "1";

            var rebillEvent = new ewayRecurringWebService.RebillEventDetails();
            rebillEvent = soap.CreateRebillEvent(ref header, rebillCustomerID, trxnReference, "courseID:" + course_price.Course_Id + "-" + course_price.Payment_Type,
                cardName, cardNum, exM, exY, initAmt, initDate, recurAmt, startDate, interval.ToString(), rebillIntervalType, rebillEndDate);

            // var result = rebillEvent.Result;
            soap.Close();
            return rebillEvent;
        }

        //Query rebill transactions
        public ewayRecurringWebService.rebillTransaction[] QueryTransactions(string rebillCustomerID, string rebillID)
        {
            var soap = new ewayRecurringWebService.manageRebillSoapClient("manageRebillSoap");
            soap.Open();
            var header = new ewayRecurringWebService.eWAYHeader();
            header.eWAYCustomerID = "87654321";
            header.Username = "test@eway.com.au";
            header.Password = "test123";

            var temp = soap.QueryTransactions(header, rebillCustomerID, rebillID, null, null, null);
            var transactions = new ewayRecurringWebService.rebillTransaction[temp.Length];
            transactions = temp;
            soap.Close();
            return transactions;
        }

        //ProcessDirectPayment and ProcessRebillPayment are using eway test gateway and test customer ID currently.
        //To use live gateway and live customer ID, cancel comments of live gateway URL and modify customer ID in web.config <appSettings> and <endPoint>

        public GatewayRequest getEWayDirectPaymentRequest(Student student, string trxnReference, Course_Price course_price, string cardName, string cardNum, string exM, string exY, string cvn)
        {
            //create eWAY gateway object
            GatewayConnector eWAYgateway = new GatewayConnector();
            GatewayRequest eWAYRequest = new GatewayRequest();

            try
            {
                // Set the payment details

                //get eWAYcustomerID from web config
                eWAYRequest.EwayCustomerID = ConfigurationManager.AppSettings["ewayCustomerID"];

                //get values input by user on form
                eWAYRequest.CardNumber = cardNum;
                eWAYRequest.CardExpiryMonth = exM;
                eWAYRequest.CardExpiryYear = exY;
                eWAYRequest.CardHolderName = cardName;

                //In eway, transaction amount is presented in cent base
                //Eg. $10.00 is presented as 1000 for eway
                string a = course_price.Total_Price.ToString().Replace(".", "");
                int aa = 0;
                int.TryParse(a, out aa);
                eWAYRequest.InvoiceAmount = aa;

                eWAYRequest.PurchaserFirstName = student.First_Name;
                eWAYRequest.PurchaserLastName = student.Last_Name;
                eWAYRequest.PurchaserEmailAddress = student.Email;
                eWAYRequest.PurchaserAddress = student.Address;
                eWAYRequest.PurchaserPostalCode = student.Postcode.ToString();
                eWAYRequest.InvoiceReference = student.First_Name + " " + student.Last_Name;
                eWAYRequest.InvoiceDescription = "courseID:" + course_price.Course_Id + "-" + course_price.Payment_Type;
                eWAYRequest.TransactionNumber = trxnReference;
                eWAYRequest.CVN = cvn;

                return eWAYRequest;
            }

                // eway exception
            catch (Exception ex)
            {
                string strErrorMessage = "<!-- " + ex.Source + "\r\n" +
                    ex.Message + "\r\n" +
                    ex.StackTrace + "\r\n-->";

                //exception occured 
                //lblResult.Text = strErrorMessage;
            }
            return null;
        }

        public GatewayResponse getEWayDirectPaymentResponse(GatewayRequest eWAYRequest)
        {
            //create eWAY gateway object
            GatewayConnector eWAYgateway = new GatewayConnector();
            try
            {
                // Do the payment, send XML doc containing information gathered
                if (eWAYgateway.ProcessRequest(eWAYRequest))
                {
                    // payment succesfully sent to gateway
                    GatewayResponse eWAYResponse = eWAYgateway.Response;
                    return eWAYResponse;
                }
            }
                // eway exception
            catch (Exception ex)
            {
                string strErrorMessage = "<!-- " + ex.Source + "\r\n" +
                    ex.Message + "\r\n" +
                    ex.StackTrace + "\r\n-->";

                //exception occured 
                //lblResult.Text = strErrorMessage;
            }
            return null;
        }

        //generate random numbers for trxn
        public string RandamNumberGenerator()
        {
            var chars = "0123456789";
            var random = new Random();
            var result = new string(
            Enumerable.Repeat(chars, 8)
            .Select(s => s[random.Next(s.Length)])
            .ToArray());
            return result;
        }

        //
        // GET: /Student/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        //
        // POST: /Student/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Student student)
        {
            if (ModelState.IsValid)
            {
                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }

        //
        // GET: /Student/Delete/5
        public ActionResult Delete(int id = 0)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        //
        // POST: /Student/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Student student = db.Students.Find(id);
            db.Students.Remove(student);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }


        //generate dropdownlist for title used by personal info form.
        public List<SelectListItem> getTitleItems(string selected)
        {
            string[] titleList = new string[5];
            titleList[0] = "Mr";
            titleList[1] = "Mrs";
            titleList[2] = "Miss";
            titleList[3] = "Ms";
            titleList[4] = "Dr";
            List<SelectListItem> TitleItems = new List<SelectListItem>();
            foreach (var title in titleList)
            {
                if (title.Equals(selected))
                {
                    TitleItems.Add(new SelectListItem { Selected = true, Text = title, Value = title });
                }
                else 
                {
                    TitleItems.Add(new SelectListItem { Text = title, Value = title });
                }
            }
            /*
            TitleItems.Add(new SelectListItem { Selected = true, Text = "Mr", Value = "Mr" });
            TitleItems.Add(new SelectListItem { Text = "Mrs", Value = "Mrs" });
            TitleItems.Add(new SelectListItem { Text = "Miss", Value = "Miss" });
            TitleItems.Add(new SelectListItem { Text = "Ms", Value = "Ms" });
            TitleItems.Add(new SelectListItem { Text = "Dr", Value = "Dr" });
             * */
            return TitleItems;
        }
    }
}